﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;  

public class PlayerController : MonoBehaviour {

	public static PlayerController instance;

	private float Hp = 10000;//血
	private float currHp = 0;//当前血量
	protected float resistanceLaser = 1;//激光抗性
	protected float resistanceMissile = 1;//导弹抗性
	protected float resistanceBullet = 1;//实弹抗性
	protected float recoverHP = 0;//恢复能力
	protected float defendPower = 1;//防御力

	public int frameCountPerscounds = 10;//每秒帧数
	public Sprite[] Sprites;//每帧动画图片集合
	private SpriteRenderer spriteRenderer;
	public bool isDeath = false;//是否死亡
	private float timer = 0;//飞机飞行时间
	private int frameIndex = 0;//当前运行到多少帧
	private int frame = 0;//设置spriteRenderer图片的索引

	public float speed = 5f;//速度
    private bool isMove = false;//是否正在移动
	private Vector3 screenPosition;//Player的屏幕坐标
	private Vector3 mousePositionInWorld;//鼠标位置的世界坐标轴
	private Vector3 mousePositionOnScreen;//鼠标位置的屏幕坐标轴
	private Vector3 movePoint;//点击位置的坐标轴
	private Rigidbody2D rigidbody2D;
	private float rotateAngle;
	private float MAX_ROTATION = 30;// 每秒最大可旋转的角度.
	private float max_rotation = 5f; // 每帧最大可旋转的角度.

	public bool isProtege = false;//是否被护盾保护



	/// <summary>
	/// Awake is called when the script instance is being loaded.
	/// </summary>
	void Awake()
	{
		instance = this;
		rigidbody2D = this.GetComponent<Rigidbody2D>();
		spriteRenderer = this.GetComponent<SpriteRenderer>();
	}
	
	/// <summary>
	/// Start is called on the frame when a script is enabled just before
	/// any of the Update methods is called the first time.
	/// </summary>
	void Start()
	{
		currHp = Hp;
        //		currHp = 8000;
    }
	
	

	void Update () {
       BgManager.instance.SetBgLocation(transform);
	   RecoverHp();
	   if(transform.Find("Shield(Clone)") != null)
	   {
		   isProtege = true;
	   }
	   else
	   {
		   isProtege = false;
	   }
	}

	/// <summary>
	/// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
	/// </summary>
	void FixedUpdate()
	{

		

		PlayAnimation();
		if (Input.GetMouseButtonDown(0) || Input.GetMouseButton(0))
        {
			if(!EventSystem.current.IsPointerOverGameObject()){
				isMove = true;
				SetPosition();
			}
            
        }
		if(Vector3.Distance(transform.position, movePoint) < 0.5){
            isMove = false;
        }
        if (isMove)
        {
            // PlayerMove();
        }
	}





	/*
	设置飞机和鼠标的坐标
	 */
	private void SetPosition(){
			//获取Player的屏幕坐标
			screenPosition = Camera.main.WorldToScreenPoint(this.transform.position);
			//获取鼠标位置的坐标轴
			mousePositionOnScreen = Input.mousePosition;
			mousePositionOnScreen.z = screenPosition.z;
			mousePositionInWorld = Camera.main.ScreenToWorldPoint(mousePositionOnScreen);
			//保存鼠标点击位置的坐标轴
			movePoint = mousePositionInWorld;

			
	}

	/*
	玩家移动
	 */
	public void PlayerMove(){
		
			//转向目标
      		float dx = movePoint.x - this.transform.position.x;
       		float dy = movePoint.y - this.transform.position.y;
            //Atan2返回弧度，用数学公式转换为角度
      		// float rotationZ = Mathf.Atan2(dy, dx) * 180 / Mathf.PI;
			float rotationZ = Mathf.Atan2(dy, dx) * Mathf.Rad2Deg;
			

       		//得到最终的角度并且确保在 [0, 360) 这个区间内     
        	rotationZ -= 90;
        	rotationZ = MakeSureRightRotation(rotationZ);

        	//获取增加的角度
        	float originRotationZ = MakeSureRightRotation(this.transform.eulerAngles.z);
        	// float addRotationZ = rotationZ - originRotationZ;
			float addRotationZ = MakeSureRightRotation(rotationZ - originRotationZ);

        	//超过 180 度需要修改为负方向的角度
        	if (addRotationZ > 180)
        	{	
            	addRotationZ -= 360;
        	}
			
			

        	//不超过每帧最大可旋转的阀值
        	addRotationZ = Mathf.Max(-max_rotation, Mathf.Min(max_rotation, addRotationZ));
			
			//应用旋转
        	this.transform.eulerAngles = new Vector3(0, 0, this.transform.eulerAngles.z + addRotationZ);
        	//移动
        	// this.transform.Translate(new Vector3(0,speed * Time.deltaTime, 0));

	}


	/*
	用于摇杆
	*/
	public void GetMoveEulerAngle(Vector2 diration){
		if(diration.x !=0 || diration.y !=0){
			float dx = diration.x;
       		float dy = diration.y;
      		float rotationZ = Mathf.Atan2(dy, dx) * 180 / Mathf.PI;
       		//得到最终的角度并且确保在 [0, 360) 这个区间内
        	rotationZ -= 90;
        	rotationZ = MakeSureRightRotation(rotationZ);
			//Tani
        	//获取增加的角度
        	float originRotationZ = MakeSureRightRotation(this.transform.eulerAngles.z);
        	float addRotationZ = rotationZ - originRotationZ;
        	//超过 180 度需要修改为负方向的角度
        	if (addRotationZ > 180)
        	{
            	addRotationZ -= 360;
        	}else if(addRotationZ < -180)
			{
				addRotationZ += 360;
			}
        	//不超过每帧最大可旋转的阀值
        	addRotationZ = Mathf.Max(-max_rotation, Mathf.Min(max_rotation, addRotationZ));
			//应用旋转
        	this.transform.eulerAngles = new Vector3(0, 0, this.transform.eulerAngles.z + addRotationZ);
		}
	}





	private float MakeSureRightRotation(float rotation)
      {
            rotation += 360;
            rotation %= 360;
            return rotation;
      }


	  /*
	  播放动画
	   */
	  private void PlayAnimation(){
		//如果飞机没死，喷射动画
		if(!isDeath){
			timer += Time.deltaTime;
			frameIndex = (int)(timer/(1f/frameCountPerscounds));
			frame = frameIndex % 2;
			spriteRenderer.sprite = Sprites[frame];
		}
		//否则，爆炸动画,销毁对象
		else{

		}
	  }


	  /*
	  造成伤害
	   */
	public void TakeDamage(float damage)
	{
		if(!isProtege)
		{
			if(currHp <= 0)return;
			currHp -= damage;
			if(currHp <= 0)
			{
				isDeath = true;
				print("玩家死了");
				/*
				播放死亡动画
				*/
				Destroy(gameObject);
			}
		}
		
	}




	private void OnTriggerEnter2D(Collider2D collision)
	{
		// print("hero.currHp--->" + currHp);
			if (collision.tag=="Enemy")
			{
				
			}
    }




	public void SetRecoverHp(float recoverHP)
	{
		this.recoverHP += recoverHP;
	}

	public void RecoverHp(float recoverHP=0)
	{
		if(currHp < Hp)
		{
			float bufferHp = currHp + recoverHP;
			if(bufferHp < Hp)
			{
				currHp = bufferHp;
			}
			else
			{
				currHp = Hp;
			}
		}
//		 print("currHp----->" + currHp);

	}





}
